package cn.git.future;

import java.util.concurrent.*;

/**
 * @description: 多个线程，都完成再处理带参数
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-08-07
 */
public class CompletableFutureDemo06 {

    static ThreadPoolExecutor executor = new ThreadPoolExecutor(
            5,
            50,
            10,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(100),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy());

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 没有返回结果，串行执行任务
        final CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            System.out.println("子线程1执行了：" + Thread.currentThread().getName());
        }, executor).thenRunAsync(() -> {
            System.out.println("子线程2执行了：" + Thread.currentThread().getName());
        }, executor);

        // 串行执行任务
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("子线程3执行了：" + Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 100;
        }, executor).exceptionally((e) -> {
            // 线程3执行结果作为线程4入参参数
            System.out.println("子线程4执行了：" + Thread.currentThread().getName());
            System.out.println("子线程4执行异常了：" + e.getMessage());
            return -1;
        });

        // 两个任务都执行完成后，执行线程5,带有返回参数
        future1.thenAcceptBothAsync(future2, (param1, param2) -> {
            // param1 = 线程3执行结果, param2 = 线程4执行结果
            System.out.println("线程5参数1 = " + param1);
            System.out.println("线程5参数2 = " + param2);
            System.out.println("子线程5执行了：" + Thread.currentThread().getName());
        });

    }
}
